package handler

import (
	"github.com/gin-gonic/gin"
	"phone-guard/model"
	"strconv"
)

func AddStudent(c *gin.Context) {
	Name := c.PostForm("name")
	StudentId, _ := strconv.Atoi(c.PostForm("student_id"))
	Class := c.PostForm("class")
	if Name == "" || StudentId == 0 || Class == "" {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := model.Student{
		Name:      Name,
		StudentId: StudentId,
		Class:     Class,
	}

	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}

func ListStudent(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var goods []model.Student
	model.DB.Offset(offset).Limit(size).Find(&goods)

	var total int64
	model.DB.Model(model.Student{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   goods,
		"total": total,
	})
	return
}
